from django.shortcuts import render,redirect,HttpResponse
from app01.models import Department,UserInfo,PhoneNumber
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
from django.utils.safestring import mark_safe
from app01.utils.pagination import Pagination
from django import forms
from app01.utils.bootstrapmodel import BootStrapModelForm


class PhonenumModelForm(forms.ModelForm):
    # mobilenumber=forms.CharField(
    #     label='手机号码',
    #     validators=[RegexValidator(r'^159[0-9]+$', '数字必须是 159 开头的')],
    # )
    class Meta:
        model=PhoneNumber
        # fields=['mobilenumber','level','stat
#         # exclude=['level']#除去level的其它字段us','price']
        fields='__all__'#所有字段
    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)
        for name,field in self.fields.items():
            field.widget.attrs={'class':'form-control','placeholder':field.label}
    #验证方法2
    def clean_mobilenumber(self):
        #获取用户传入的mobile钩子方法
        txt_mobile=self.cleaned_data['mobilenumber']
        exists=PhoneNumber.objects.filter(mobilenumber=txt_mobile).exists()
        if exists:
            raise ValidationError('手机号已存在')
        elif len(txt_mobile)!=11:
            #验证不通过
            raise ValidationError('格式错误')
        #验证通过，用户输入的值返回
        return txt_mobile
# class PhonenumModelForm(forms.ModelForm):
#     '''员工表'''
#     class Meta:
#         model=PhoneNumber
#         fields='__all__'
#
#     def __init__(self,*args,**kwargs):
#         super().__init__(*args,**kwargs)
#         #循环找到所有的插件添加属性
#         for name,field in self.fields.items():
#             field.widget.attrs={'class':'form-control','placeholder':field.label}
from app01.utils.pagination import Pagination
def phonenum_list(request):
    '''靓号列表'''
    from django.http.request import QueryDict
    import copy
    get_object=copy.deepcopy(request.GET)
    get_object._mutable=True
    get_object.setlist('page',[10])
    print(get_object.urlencode())
    print(type(get_object))
    print(request.GET)
    print(request.GET.urlencode())
    # q1=PhoneNumber.objects.filter(mobilenumber='12312312312',id=10)
    # print(q1)
    # data_dic={'mobilenumber':'12312312312',"id":10}
    # q2=PhoneNumber.objects.filter(**data_dic)
    # print(q2)
    # for i in range(300):#创建300条数据
    #     PhoneNumber.objects.create(mobilenumber='12345678123',price=100,level=1,status=1)
    data_dic={}
    search_data=request.GET.get('q','')#如果值不存在就返回空
    if search_data:
        data_dic={'mobilenumber__contains':search_data}
    # res=PhoneNumber.objects.filter(**data_dic)
    # print(res)
    # from app01.utils.pagination import Pagination
    queryset=PhoneNumber.objects.filter(**data_dic).order_by("-level")
    page_object=Pagination(request,queryset)
    # page_quertyset=page_object.queryset
    #根据用户想要访问的页码，计算出起止位置
    # page=int(request.GET.get('page',1))#如果page没有值就返回第一页
    # pagesize=10
    # start=(page-1)*pagesize
    # end=(page)*pagesize
    # print(f'end is {end}')
    #select * from PhoneNumber order by id asc 升序排序
    #总条数
    # total_count=PhoneNumber.objects.filter(**data_dic).order_by("-level").count()#id asc -id desc
    # #计算出总页码
    # total_page_count,div=divmod(total_count,pagesize)
    # if div:
    #     total_page_count+=1
    # phonelist=PhoneNumber.objects.filter(**data_dic).order_by("-level")[page_object.start:page_object.end]#id asc -id desc
    # 页码
    #计算出当前页的前五页，后5页

    # page_string=mark_safe(''.join(page_str_list))
    # page_string=page_object.html()
    context={'phonelist':page_object.page_queryset,#分页后的数据
             'search_data':search_data,
             'page_string':page_object.html()}#生成的页码
    return render(request,'phone_list.html',context)

def phonenum_add(request):
    if request.method=='GET':
        form=PhonenumModelForm()
        print(form)
        return render(request,'phone_add.html',{'form':form})

    form=PhonenumModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect('/phonenum/list/')
    else:
        print(form.errors)
        return render(request,'phone_add.html',{'form':form})

def phonenum_del(request,nid):
    PhoneNumber.objects.filter(id=nid).delete()
    return redirect('/phonenum/list/')
class PhoneNumEditMobile(forms.ModelForm):
    # mobilenumber=forms.CharField(disabled=True,label='手机号')
    class Meta:
        model=PhoneNumber
        fields=['mobilenumber','level','status','price']

    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)
        for name,field in self.fields.items():
            field.widget.attrs = {'class': 'form-control', 'placeholder': field.label}
            # 验证方法2
    def clean_mobilenumber(self):
        #当前编辑的是那一行的ID
        print(self.instance.pk)
        txt_mobile=self.cleaned_data['mobilenumber']
        exits=PhoneNumber.objects.exclude(id=self.instance.pk).filter(mobilenumber=txt_mobile).exists()
        print(exits)
        if exits:
            # raise ValidationError('手机号已存在')
            raise ValidationError('格式错误')
            # 验证通过，用户输入的值返回
        return txt_mobile
def phonenum_edit(request,nid):
    rowobj=PhoneNumber.objects.filter(id=nid).first()
    if request.method=='GET':
        form=PhoneNumEditMobile(instance=rowobj)
        return render(request,'phone_edit.html',{'form':form})
    form=PhoneNumEditMobile(data=request.POST,instance=rowobj)
    form.save()
    return redirect('/phonenum/list/')